#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024

int main() {
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0) {
        perror("socket");
        exit(1);
    }

    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(8080),
        .sin_addr.s_addr = INADDR_ANY
    };

    if (bind(server_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("bind");
        close(server_fd);
        exit(1);
    }

    if (listen(server_fd, 5) < 0) {
        perror("listen");
        close(server_fd);
        exit(1);
    }

    fd_set read_fds;
    int client_fds[MAX_CLIENTS] = {0};
    int max_fd = server_fd;

    printf("服务器启动，监听端口8080...\n");
    while (1) {
        FD_ZERO(&read_fds);
        FD_SET(server_fd, &read_fds);
        for (int i = 0; i < MAX_CLIENTS; i++) {
            if (client_fds[i] > 0) FD_SET(client_fds[i], &read_fds);
            if (client_fds[i] > max_fd) max_fd = client_fds[i];
        }

        int activity = select(max_fd + 1, &read_fds, NULL, NULL, NULL);
        if (activity < 0) {
            perror("select");
            continue;
        }

        // 处理新连接
        if (FD_ISSET(server_fd, &read_fds)) {
            struct sockaddr_in client_addr;
            socklen_t addr_len = sizeof(client_addr);
            int client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &addr_len);
            if (client_fd < 0) {
                perror("accept");
                continue;
            }
            printf("新客户端连接：%s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

            // 将新客户端加入数组
            for (int i = 0; i < MAX_CLIENTS; i++) {
                if (client_fds[i] == 0) {
                    client_fds[i] = client_fd;
                    break;
                }
            }
        }

        // 处理客户端数据
        for (int i = 0; i < MAX_CLIENTS; i++) {
            int fd = client_fds[i];
            if (fd > 0 && FD_ISSET(fd, &read_fds)) {
                char buffer[BUFFER_SIZE];
                ssize_t len = recv(fd, buffer, sizeof(buffer), 0);
                if (len <= 0) {
                    printf("客户端断开连接\n");
                    close(fd);
                    client_fds[i] = 0;
                } else {
                    buffer[len] = '\0';
                    printf("收到数据：%s\n", buffer);
                    send(fd, buffer, len, 0);
                }
            }
        }
    }

    close(server_fd);
    return 0;
}
